//
//  CAICameraBottomPreviewPhotosView.m
//  CAIImagePickerControllerKit
//
//  Created by 海参 on 2022/8/4.
//

#import "CAICameraBottomPreviewPhotosView.h"
#import <Masonry/Masonry.h>
#import "CAICameraBottomPreviewPhotoCell.h"
#import "CAIImagePickerKitTool.h"


@interface CAICameraBottomPreviewPhotosView ()

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *collectionFlowLayout;
/// default is UICollectionViewScrollDirectionVertical
@property (nonatomic) UICollectionViewScrollDirection scrollDirection;

@property (nonatomic, strong) NSMutableArray *dataMArray;

@end

@implementation CAICameraBottomPreviewPhotosView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    self.picItemWidth = 80;
    self.picItemHeight = 80;
    self.picItemLayoutTop = 9;
    self.picItemLayoutRight = 9;
    
    self.minimumInteritemSpacing = 12;
    self.minimumLineSpacing = 12;
    
    self.showItemDeleteIconButton = YES;
    [self addSubview:self.collectionView];
    self.backgroundColor = [UIColor whiteColor];
    [self addConstraint];
}

- (void)addConstraint
{
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
}


#pragma mark - UI

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        self.collectionFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView *collection = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.collectionFlowLayout];
        collection.backgroundColor = [UIColor whiteColor];
        collection.delegate = self;
        collection.dataSource = self;
        
        [collection registerClass:[CAICameraBottomPreviewPhotoCell class] forCellWithReuseIdentifier:@"Cell"];
        collection.scrollEnabled = YES;
        collection.showsVerticalScrollIndicator = NO;
        collection.showsHorizontalScrollIndicator = NO;
        _collectionView = collection;
    }
    return _collectionView;
}


- (UICollectionViewFlowLayout *)collectionFlowLayout{
    if (!_collectionFlowLayout) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionFlowLayout = flowLayout;
    }
    return _collectionFlowLayout;
}

#pragma mark - 初始化数据

- (NSMutableArray *)dataMArray
{
    if (!_dataMArray)
    {
        _dataMArray = [NSMutableArray array];
    }
    return _dataMArray;
}


- (void)setBackgroundColor:(UIColor *)backgroundColor{
    self.collectionView.backgroundColor = backgroundColor;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger count = [self getMaxNumberOfItemsInSection:self.dataMArray];
    return count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //因为cell右上角放删除按钮，所以左右上下各增加10个距离；
    CAICameraBottomPreviewPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.picItemLayoutTop = self.picItemLayoutTop;
    cell.picItemLayoutRight = self.picItemLayoutRight;
    if (self.pointColor) {
        cell.pointColor = self.pointColor;
    }
    [cell reloadLayout];
    [cell.deleteButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.hidden = !self.showItemDeleteIconButton;
    id data = [self.dataMArray objectAtIndex:indexPath.item];
    [cell setData:data];
    return cell;
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return self.sectionInset;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return self.minimumLineSpacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return self.minimumInteritemSpacing;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self itemSize];
}


- (CGSize)itemSize{
    CGSize size =  CGSizeMake(self.picItemWidth+self.picItemLayoutRight, self.picItemHeight+self.picItemLayoutTop + LCDScale_iPhone6(14));
    return size;
}


#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"selectItem = %@",@(indexPath.item));
    [self.dataMArray enumerateObjectsUsingBlock:^(CAIUIImagePickerCameraPhotoModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (indexPath.item == idx) {
            obj.selected = YES;
        }
    }];
//    [collectionView reloadData];
    if ([self.delegate respondsToSelector:@selector(cameraBottomPreviewPhotosView:didSelectPicItemAtIndex:photos:)])
    {
        [self.delegate cameraBottomPreviewPhotosView:self didSelectPicItemAtIndex:indexPath.item photos:[self.dataMArray copy]];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"deselectItem = %@",@(indexPath.item));
    [self.dataMArray enumerateObjectsUsingBlock:^(CAIUIImagePickerCameraPhotoModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (indexPath.item == idx) {
            obj.selected = NO;
        }
    }];
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"shouldSelectItem = %@",@(indexPath.item));
//    if (indexPath.item == 0) {
//        return NO;
//    }
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"shouldDeselectItem = %@",@(indexPath.item));
    return YES;
}

#pragma mark - setter方法

- (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection{
    if (_scrollDirection != scrollDirection) {
        _scrollDirection = scrollDirection;
        self.collectionFlowLayout.scrollDirection = scrollDirection;
    }
}

#pragma mark - 计算方法

//计算高度
- (CGFloat)getTotalHeightWithRows:(NSInteger)rows{
    if (rows == 0) {
        return 0;
    }
    CGSize itemSize = [self itemSize];
    if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal){
        CGFloat height = rows * itemSize.height + (rows - 1) * self.minimumInteritemSpacing +self.sectionInset.top+self.sectionInset.bottom;
        return ceilf(height);
    }else{
        CGFloat height = rows * itemSize.height + (rows - 1) * self.minimumLineSpacing +self.sectionInset.top+self.sectionInset.bottom;
        return ceilf(height);
    }
}

/// 获取Item总个数
- (NSInteger)getMaxNumberOfItemsInSection:(nullable NSArray *)data
{
    NSInteger count = 0;
    if (self.maxItemCount == 0){
        count = data.count;
    }else{
        count = data.count<self.maxItemCount?data.count:self.maxItemCount;
    }
    return count;
}


#pragma mark - 实例方法

- (void)setData:(NSArray<CAIUIImagePickerCameraPhotoModel *> *)data
{
    [self.dataMArray removeAllObjects];
    if ([data count] > self.maxItemCount && self.maxItemCount >0)
    {
        NSRange range = NSMakeRange(0, self.maxItemCount);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        data = [NSMutableArray arrayWithArray:[data objectsAtIndexes:set]];
    };
    [self.dataMArray addObjectsFromArray:data];
    if ([self.collectionView isDescendantOfView:self]) {
        [self.collectionView reloadData];
    }
}


- (void)scrollToItemAtIndex:(NSInteger)index{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionRight|UICollectionViewScrollPositionBottom animated:YES];
}


- (void)selectItemAtIndex:(NSInteger)index{
    if (self.collectionView.visibleCells.count == 0) {
//        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
//        dispatch_after(time,dispatch_get_main_queue(), ^{
//            [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally|UICollectionViewScrollPositionCenteredVertically];
//        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally|UICollectionViewScrollPositionCenteredVertically];
        });
    }else{
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally|UICollectionViewScrollPositionCenteredVertically];
    }
}

#pragma mark - 删除事件

- (void)deleteAction:(UIButton *)sender
{
    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath* indexPath = [self.collectionView indexPathForItemAtPoint:point];
    
    [self.dataMArray removeObjectAtIndex:indexPath.item];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    if ([self.delegate respondsToSelector:@selector(cameraBottomPreviewPhotosView:commitEditingForRowAtIndexPath:)]) {
        [self.delegate cameraBottomPreviewPhotosView:self commitEditingForRowAtIndexPath:indexPath];
    }
}



@end
